<template>
  <el-dialog
    :title="optionType === 'add' ? '添加日反馈记录' : '修改日反馈记录'"
    :visible.sync="visible"
    width="950px"
    :before-close="handleClose"
    :modal-append-to-body="false"
    :append-to-body="true"
  >
    <div id="feedbackRecordForm">
      <div class="feedback-record-container">
        <!-- 表头信息 -->
        <div class="header-info">
          <h2 class="title">
            {{ form.school_name || "厦门市新景幼儿园" }}
            {{ form.semester_name || "2025-2026 学年第一学期" }}
            {{ form.class_name || "托大班" }}
          </h2>
          <h3 class="subtitle">日反馈记录表 <span style="font-size: 12pt;margin-left: 20px;">记录人：{{ form.recorder || "-" }}</span></h3>
        </div>


        <!-- 基本信息表格 -->
        <div class="basic-info-table">
          <table>
            <tbody>
              <tr>
                <td class="info-label">时间</td>
                <td class="info-value" style="width: 180px;">{{ form.date || "年 月 日" }}</td>
                <td class="info-label" style="width: 120px;">幼儿姓名</td>
                <td class="info-value" style="width: 120px;">{{ form.student_name || "" }}</td>
                <td class="info-label" style="width: 80px;">体温</td>
                <td class="info-value">{{ form.temperature || "" }}</td>
              </tr>
            </tbody>
          </table>
        </div>

        <!-- 反馈事项表格 -->
        <div class="feedback-table-wrapper">
          <table class="feedback-content-table" v-if="feedbackCateList.length">
            <tbody>
              <template v-for="(category, categoryIndex) in feedbackCateList">
                <!-- 处理有子分类的一级事项 -->
                <template v-if="category.children && category.children.length > 0">
                  <!-- 第一个子分类行包含一级事项 -->
                  <tr>
                    <td class="category-cell" :rowspan="category.children.length">
                      <span class="category-number">{{ categoryIndex + 1 }}.</span>
                      <span class="category-name">{{ category.name }}</span>
                    </td>
                    <td class="content-cell">
                      <div class="subcategory-content">
                        <span class="subcategory-title">{{ category.children[0].name }}:</span>
                        <!-- 子分类内容 -->
                        <div class="subcategory-options">
                          <template v-if="category.children[0].type === 0">
                            <!-- 选项类型 -->
                            <div v-if="category.children[0].description && category.children[0].description.trim()">
                              <span
                                v-for="(optionText, optionIndex) in category.children[0].description
                                  .split(';')
                                  .map((opt) => opt.trim())
                                  .filter((opt) => opt)"
                                :key="optionIndex"
                                class="option-item"
                                @click="selectChoice(category.children[0], optionText)"
                                :class="{
                                  'selected': dynamicFeedbackOptions[category.children[0].id] &&
                                            dynamicFeedbackOptions[category.children[0].id].includes(optionText)
                                }"
                              >
                                <span class="checkbox">{{ dynamicFeedbackOptions[category.children[0].id] &&
                                          dynamicFeedbackOptions[category.children[0].id].includes(optionText) ? '✓' : '□' }}</span>
                                <span class="option-text">{{ optionText }}</span>
                              </span>
                            </div>
                            <!-- 有options数组时渲染选项 -->
                            <div v-else-if="category.children[0].options && category.children[0].options.length > 0">
                              <span
                                v-for="option in category.children[0].options"
                                :key="option.id"
                                class="option-item"
                                @click="selectChoice(category.children[0], option.id)"
                                :class="{
                                  'selected': dynamicFeedbackOptions[category.children[0].id] &&
                                            dynamicFeedbackOptions[category.children[0].id].includes(option.id)
                                }"
                              >
                                <span class="checkbox">{{ dynamicFeedbackOptions[category.children[0].id] &&
                                          dynamicFeedbackOptions[category.children[0].id].includes(option.id) ? '✓' : '□' }}</span>
                                <span class="option-text">{{ option.name }}</span>
                              </span>
                            </div>
                          </template>
                          <!-- 文本输入类型 -->
                          <div v-else-if="category.children[0].type === 1">
                            <el-input
                              v-model="dynamicFeedbackOptions[category.children[0].id]"
                              type="text"
                              placeholder="请输入内容"
                              size="small"
                              class="feedback-input"
                            ></el-input>
                          </div>
                          <!-- 文件类型 -->
                          <div v-else-if="category.children[0].type === 2">
                            <div v-if="dynamicFeedbackOptions[category.children[0].id] && dynamicFeedbackOptions[category.children[0].id].length > 0">
                              <div v-for="(file, fileIndex) in dynamicFeedbackOptions[category.children[0].id]" :key="fileIndex">
                                <a :href="file.url" target="_blank" class="file-link">{{ file.name }}</a>
                              </div>
                            </div>
                            <div v-else class="no-file">暂无文件</div>
                          </div>
                        </div>
                      </div>
                    </td>
                  </tr>
                  <!-- 其余子分类行 -->
                  <tr v-for="(subCategory, subIndex) in category.children.slice(1)" :key="subCategory.id">
                    <td class="content-cell">
                      <div class="subcategory-content">
                        <span class="subcategory-title">{{ subCategory.name }}:</span>
                        <!-- 子分类内容 -->
                        <div class="subcategory-options">
                          <template v-if="subCategory.type === 0">
                            <!-- 选项类型 -->
                            <div v-if="subCategory.description && subCategory.description.trim()">
                              <span
                                v-for="(optionText, optionIndex) in subCategory.description
                                  .split(';')
                                  .map((opt) => opt.trim())
                                  .filter((opt) => opt)"
                                :key="optionIndex"
                                class="option-item"
                                @click="selectChoice(subCategory, optionText)"
                                :class="{
                                  'selected': dynamicFeedbackOptions[subCategory.id] &&
                                            dynamicFeedbackOptions[subCategory.id].includes(optionText)
                                }"
                              >
                                <span class="checkbox">{{ dynamicFeedbackOptions[subCategory.id] &&
                                          dynamicFeedbackOptions[subCategory.id].includes(optionText) ? '✓' : '□' }}</span>
                                <span class="option-text">{{ optionText }}</span>
                              </span>
                            </div>
                            <!-- 有options数组时渲染选项 -->
                            <div v-else-if="subCategory.options && subCategory.options.length > 0">
                              <span
                                v-for="option in subCategory.options"
                                :key="option.id"
                                class="option-item"
                                @click="selectChoice(subCategory, option.id)"
                                :class="{
                                  'selected': dynamicFeedbackOptions[subCategory.id] &&
                                            dynamicFeedbackOptions[subCategory.id].includes(option.id)
                                }"
                              >
                                <span class="checkbox">{{ dynamicFeedbackOptions[subCategory.id] &&
                                          dynamicFeedbackOptions[subCategory.id].includes(option.id) ? '✓' : '□' }}</span>
                                <span class="option-text">{{ option.name }}</span>
                              </span>
                            </div>
                          </template>
                          <!-- 文本输入类型 -->
                          <div v-else-if="subCategory.type === 1">
                            <el-input
                              v-model="dynamicFeedbackOptions[subCategory.id]"
                              type="text"
                              placeholder="请输入内容"
                              size="small"
                              class="feedback-input"
                            ></el-input>
                          </div>
                          <!-- 文件类型 -->
                          <div v-else-if="subCategory.type === 2">
                            <div v-if="dynamicFeedbackOptions[subCategory.id] && dynamicFeedbackOptions[subCategory.id].length > 0">
                              <div v-for="(file, fileIndex) in dynamicFeedbackOptions[subCategory.id]" :key="fileIndex">
                                <a :href="file.url" target="_blank" class="file-link">{{ file.name }}</a>
                              </div>
                            </div>
                            <div v-else class="no-file">暂无文件</div>
                          </div>
                        </div>
                      </div>
                    </td>
                  </tr>
                </template>
                
                <!-- 处理没有子分类但有类型的一级事项 -->
                <tr v-else-if="category.type !== undefined" :key="category.id">
                  <td class="category-cell">
                    <span class="category-number">{{ categoryIndex + 1 }}.</span>
                    <span class="category-name">{{ category.name }}</span>
                  </td>
                  <td class="content-cell">
                    <!-- 选项类型 -->
                    <template v-if="category.type === 0">
                      <div v-if="category.description && category.description.trim()">
                        <span
                          v-for="(optionText, optionIndex) in category.description
                            .split(';')
                            .map((opt) => opt.trim())
                            .filter((opt) => opt)"
                          :key="optionIndex"
                          class="option-item"
                          @click="selectChoice(category, optionText)"
                          :class="{
                            'selected': dynamicFeedbackOptions[category.id] &&
                                      dynamicFeedbackOptions[category.id].includes(optionText)
                          }"
                        >
                          <span class="checkbox">{{ dynamicFeedbackOptions[category.id] &&
                                    dynamicFeedbackOptions[category.id].includes(optionText) ? '✓' : '□' }}</span>
                          <span class="option-text">{{ optionText }}</span>
                        </span>
                      </div>
                      <div v-else-if="category.options && category.options.length > 0">
                        <span
                          v-for="option in category.options"
                          :key="option.id"
                          class="option-item"
                          @click="selectChoice(category, option.id)"
                          :class="{
                            'selected': dynamicFeedbackOptions[category.id] &&
                                      dynamicFeedbackOptions[category.id].includes(option.id)
                          }"
                        >
                          <span class="checkbox">{{ dynamicFeedbackOptions[category.id] &&
                                    dynamicFeedbackOptions[category.id].includes(option.id) ? '✓' : '□' }}</span>
                          <span class="option-text">{{ option.name }}</span>
                        </span>
                      </div>
                    </template>
                    <!-- 文本输入类型 -->
                    <div v-else-if="category.type === 1">
                      <el-input
                        v-model="dynamicFeedbackOptions[category.id]"
                        type="text"
                        placeholder="请输入内容"
                        size="small"
                        class="feedback-input"
                      ></el-input>
                    </div>
                    <!-- 文件类型 -->
                    <div v-else-if="category.type === 2">
                      <div v-if="dynamicFeedbackOptions[category.id] && dynamicFeedbackOptions[category.id].length > 0">
                        <div v-for="(file, fileIndex) in dynamicFeedbackOptions[category.id]" :key="fileIndex" class="file-item">
                          <!-- 图片类型 -->
                          <div v-if="isImageFile(file)" class="image-preview">
                            <img :src="file.url" :alt="file.name" class="preview-image" />
                          </div>
                          <!-- 视频类型 -->
                          <div v-else-if="isVideoFile(file)" class="video-preview">
                            <video :src="file.url" controls class="preview-video">
                              您的浏览器不支持视频播放
                            </video>
                          </div>
                          <!-- 其他文件类型 -->
                          <div v-else class="file-link-container">
                            <a :href="file.url" target="_blank" class="file-link">{{ file.name }}</a>
                          </div>
                        </div>
                      </div>
                      <div v-else class="no-file">暂无文件</div>
                    </div>
                  </td>
                </tr>
              </template>
            </tbody>
          </table>
          <div v-else class="no-data">暂无反馈数据</div>
        </div>

        <!-- 操作按钮 -->
        <div class="action-buttons">
          <el-button type="primary" @click.native="exportToWord" size="small"
            >导出Word</el-button
          >
          <el-button @click.native="closePOpup" size="small">取消</el-button>
        </div>
      </div>
    </div>
  </el-dialog>
</template>

<script>
import {DailyFeedbackAdd, DailyFeedbackEdit, DailyFeedbackCateIndex} from "@/api/admin/dailyFeedback";
import {sectionIndex, classIndex} from "@/api/admin/class"
import {classesStudent} from "@/api/admin/student"
// 移除不适合浏览器环境的html-docx-js库


export default {
  props: ['visible', 'optionData', 'optionType', 'feedbackCateList'],
  components: {},
  data() {
      return {
        form: {
          section_id: '',
          class_id: '',
          student_id: '',
          student_name: '',
          school_name: '',
          class_name: '',
          section_name: '',
          feedback_items: [],
          body: '',
          recorder: '', // 记录人
          date: '', // 日期
          temperature: '' // 体温
        },
        sectionList: [],
        classList: [],
        studentList: [],
        // 动态反馈选项存储
        dynamicFeedbackOptions: {}
      }
    },
  watch: {
    visible() {
      if (this.visible) {
        this.initForm()
      } else {
        this.resetForm()
      }
    }
  },
  created() {
    this.getSectionList()
    // 初始化表单（如果有optionData，会在initForm中加载相关数据）
    this.initForm()
  },
  methods: {
    // 判断是否为图片文件
    isImageFile(file) {
      if (!file || !file.name) return false;
      const imageExtensions = ['.jpg', '.jpeg', '.png', '.gif', '.bmp', '.webp', '.svg'];
      const fileName = file.name.toLowerCase();
      return imageExtensions.some(ext => fileName.endsWith(ext));
    },
    // 判断是否为视频文件
    isVideoFile(file) {
      if (!file || !file.name) return false;
      const videoExtensions = ['.mp4', '.avi', '.mov', '.wmv', '.flv', '.webm', '.mkv'];
      const fileName = file.name.toLowerCase();
      return videoExtensions.some(ext => fileName.endsWith(ext));
    },
    handleClose(done) {
      this.closePOpup()
      if (done) {
        done()
      }
    },
    initForm() {
      if (this.optionType === 'add') {
        this.resetForm()
        // 添加模式下也获取反馈分类数据
        this.getFeedbackCateList()
      } else if (this.optionType === 'edit' && this.optionData) {
        // 编辑模式下，填充表单数据
        console.log('接收到的optionData:', this.optionData);

        // 增强版的数据映射，确保所有需要的字段都被正确赋值
        this.form = {
          section_id: this.optionData.section_id || '',
          class_id: this.optionData.class_id || '',
          student_id: this.optionData.student_id || '',
          student_name: this.optionData.student.name || '',
          school_name: this.optionData.school.name || '',
          class_name: this.optionData.classes.class_name || '',
          section_name: this.optionData.section_name || '',
          semester_name: this.optionData.semester_name || '', // 确保学期名称被正确赋值
          recorder: this.optionData.user.realname || '',
          date: this.optionData.create_time || '',
          temperature: this.optionData.temperature || '',
          body: this.optionData.body || '',
          // 确保feedback_items正确解析
          feedback_items: this.optionData.feedback_items
            ? (typeof this.optionData.feedback_items === 'string'
               ? JSON.parse(this.optionData.feedback_items)
               : this.optionData.feedback_items)
            : []
        }

        console.log('初始化后的表单数据:', this.form);

        // 表单数据初始化完成后，获取反馈分类数据
        this.getFeedbackCateList()

        // 如果有body数据，尝试解析并记录到控制台，便于调试
        if (this.form.body) {
          try {
            const bodyData = JSON.parse(this.form.body)
            console.log('解析后的body数据:', bodyData)
          } catch (e) {
            console.error('解析body数据失败:', e)
          }
        }

        // 如果有班级ID，获取班级列表并选择对应班级
        if (this.form.section_id) {
          this.getClassList(this.form.section_id)
            .then(() => {
              // 如果有学生ID，获取学生列表并选择对应学生
              if (this.form.class_id) {
                this.getStudentList(this.form.class_id)
              }
            })
        }

        // 确保分类数据已加载，如果没有则重新获取
        if (!this.feedbackCateList || this.feedbackCateList.length === 0) {
          this.getFeedbackCateList().then(() => {
            this.initFeedbackOptions()
          })
        } else {
          // 初始化反馈选项数据
          this.initFeedbackOptions()
        }
      }
    },

    // 初始化反馈选项数据
    initFeedbackOptions() {
      console.log('初始化反馈选项，分类数据:', this.feedbackCateList);
      console.log('表单数据:', this.form);

      if (!this.feedbackCateList || this.feedbackCateList.length === 0) {
        console.warn('分类数据为空，无法初始化反馈选项');
        return
      }

      // 重置动态选项对象
      this.dynamicFeedbackOptions = {};

      // 如果有body数据，尝试解析并处理
      if (this.form.body) {
        try {
          const bodyData = JSON.parse(this.form.body);
          
          // 检查数据类型
          if (Array.isArray(bodyData)) {
            // 遍历body中的数据项
            bodyData.forEach(item => {
              // 只处理有ID的项目
              if (!item.id) {
                console.warn('跳过没有ID的数据项:', item);
                return;
              }
              
              const categoryId = String(item.id);
              
              // 处理选择类型的数据 (choice字段)
              if (item.choice !== undefined) {
                console.log(`处理选项类型数据: ID=${categoryId}, choice=${item.choice}`);
                
                // 初始化该分类的选项数组
                if (!this.dynamicFeedbackOptions[categoryId]) {
                  this.dynamicFeedbackOptions[categoryId] = [];
                }
                
                // 处理单个选项或选项数组
                if (Array.isArray(item.choice)) {
                  // 添加所有选项到选中列表
                  item.choice.forEach(choice => {
                    const choiceStr = String(choice).trim();
                    if (choiceStr && !this.dynamicFeedbackOptions[categoryId].includes(choiceStr)) {
                      this.dynamicFeedbackOptions[categoryId].push(choiceStr);
                    }
                  });
                } else {
                  // 单个选项
                  const choiceStr = String(item.choice).trim();
                  if (choiceStr && !this.dynamicFeedbackOptions[categoryId].includes(choiceStr)) {
                    this.dynamicFeedbackOptions[categoryId].push(choiceStr);
                  }
                }
              }
              // 处理文本输入类型的数据 (content字段)
              else if (item.content !== undefined) {
                console.log(`处理文本类型数据: ID=${categoryId}`);
                this.dynamicFeedbackOptions[categoryId] = String(item.content || '');
              }
              // 处理文件类型的数据 (files字段)
              else if (item.files !== undefined) {
                console.log(`处理文件类型数据: ID=${categoryId}, 文件数=${item.files?.length || 0}`);
                this.dynamicFeedbackOptions[categoryId] = Array.isArray(item.files) ? item.files : [];
              }
            });
          } else {
            console.warn('body数据不是数组格式，无法处理:', bodyData);
          }
        } catch (e) {
          console.error('解析body数据失败:', e);
        }
      }

      // 处理常规的feedback_items数据（如果有的话）
      if (this.form.feedback_items && this.form.feedback_items.length > 0) {
        console.log('处理feedback_items数据，数量:', this.form.feedback_items.length);
        
        // 遍历所有分类和子分类
        this.feedbackCateList.forEach(category => {
          if (!category.children) return; // 安全检查

          category.children.forEach(subCategory => {
            if (subCategory.type === 0) {
              // 初始化一个空数组
              if (!this.dynamicFeedbackOptions[subCategory.id]) {
                this.dynamicFeedbackOptions[subCategory.id] = [];
              }

              // 筛选出当前子分类下的选中项
              const selectedOptions = this.form.feedback_items.filter(item =>
                subCategory.options && subCategory.options.some(option => String(option.id) === String(item))
              );
              if (selectedOptions.length > 0) {
                // 合并已存在的选项和新的选项，避免重复
                const mergedOptions = [...new Set([...this.dynamicFeedbackOptions[subCategory.id], ...selectedOptions])];
                this.dynamicFeedbackOptions[subCategory.id] = mergedOptions;
              }
            }
          });
        });
      }
      
      console.log('反馈选项初始化完成，数据项数量:', Object.keys(this.dynamicFeedbackOptions).length);
    },

    // 处理选项点击
    checkOption(subCategory) {
      // 这里可以添加选项点击的处理逻辑
      console.log('选项点击:', subCategory);
    },

    // 选择选项
    selectChoice(subCategory, optionId) {
      // 如果当前选项未被选中，则添加到选中列表；否则移除
      if (!this.dynamicFeedbackOptions) {
        this.dynamicFeedbackOptions = {}
      }
      if (!this.dynamicFeedbackOptions[subCategory.id]) {
        this.dynamicFeedbackOptions[subCategory.id] = []
      }

      const index = this.dynamicFeedbackOptions[subCategory.id].indexOf(optionId)
      if (index > -1) {
        this.dynamicFeedbackOptions[subCategory.id].splice(index, 1)
      } else {
        this.dynamicFeedbackOptions[subCategory.id].push(optionId)
      }
    },

    resetForm() {
      this.form = {
        section_id: '',
        class_id: '',
        student_id: '',
        student_name: '',
        class_name: '',
        section_name: '',
        feedback_items: [],
        body: ''
      }
      this.classList = []
      this.studentList = []
      // 重置动态反馈选项
      this.dynamicFeedbackOptions = {}
    },

    // 获取年段列表
    getSectionList() {
      sectionIndex().then(res => {
        if (!res.code) {
          this.sectionList = res.list.data || [];
        }
      });
    },

    // 获取反馈分类数据
    getFeedbackCateList() {
      // 构建请求参数，确保section_id有效
      console.log('获取反馈分类请求参数:', this.optionData);
      
      // 获取有效的section_id，确保不为空
      let sectionId = this.optionData?.section_id;
      // 如果section_id不存在或为空，尝试使用form中的section_id
      if (!sectionId || sectionId === '') {
        sectionId = this.form?.section_id;
        console.log('使用form中的section_id:', sectionId);
      }
      // 如果仍然为空，从sectionList中获取第一个年段ID作为默认值
      if (!sectionId || sectionId === '') {
        if (this.sectionList && this.sectionList.length > 0) {
          sectionId = this.sectionList[0].id;
          console.log('使用第一个年段ID作为默认值:', sectionId);
        } else {
          console.warn('未找到有效的section_id，将使用null');
        }
      }
      
      // 确保section_id是数字类型
      const numericSectionId = sectionId ? parseInt(sectionId) : null;
      const params = {p: 0, section_id: numericSectionId};
      
      console.log('最终请求参数:', params);
      
      DailyFeedbackCateIndex(params)
        .then(res => {
          console.log('获取反馈分类响应:', res)
          if (!res.code) {
            this.feedbackCateList = this.$handleTree(res.list, 'id', 'parent_id')
            // 如果是编辑模式，初始化反馈选项
            if (this.optionType === 'edit' && this.optionData) {
              this.initFeedbackOptions()
            }
          } else {
            this.$message.error(res.msg || '获取反馈分类失败')
          }
        })
        .catch(err => {
          console.error('获取反馈分类失败:', err)
          this.$message.error('获取反馈分类失败')
        })
    },

    // 处理年段变化
    handleSectionChange(sectionId) {
      this.form.class_id = ''
      this.form.student_id = ''
      this.classList = []
      this.studentList = []
      if (sectionId) {
        this.getClassList(sectionId)
      }
    },

    // 处理班级变化
    handleClassChange(classId) {
      this.form.student_id = ''
      this.studentList = []
      if (classId) {
        this.getStudentList(classId)
      }
    },

    // 获取班级列表
    async getClassList(sectionId) {
      return new Promise((resolve, reject) => {
        classIndex({section_id: sectionId}).then(res => {
          if (!res.code) {
            this.classList = res.list.data || [];
            resolve(this.classList);
          } else {
            reject(new Error('获取班级列表失败'));
          }
        }).catch(err => {
          console.error('获取班级列表失败:', err);
          reject(err);
        });
      });
    },

    // 获取学生列表
    async getStudentList(classId) {
      return new Promise((resolve, reject) => {
        if (!classId) {
          this.studentList = []
          resolve([]);
          return
        }
        classesStudent({class_id: classId}).then(res => {
          if (!res.code) {
            this.studentList = res.list || [];
            resolve(this.studentList);
          } else {
            reject(new Error('获取学生列表失败'));
          }
        }).catch(err => {
          console.error('获取学生列表失败:', err);
          reject(err);
        });
      });
    },



    // 收集反馈数据
    collectFeedbackData() {
      const feedbackData = [];

      // 检查form.body是否存在且为字符串
      if (this.form.body && typeof this.form.body === 'string') {
        try {
          // 尝试解析body内容
          const bodyData = JSON.parse(this.form.body);

          // 如果解析成功且是数组
          if (Array.isArray(bodyData)) {
            // 为每个反馈项创建一个映射，用于快速查找
            const bodyMap = {};
            bodyData.forEach(item => {
              if (item.id || item.name) {
                bodyMap[item.id || item.name] = item;
              }
            });

            // 遍历分类数据
            this.feedbackCateList.forEach(category => {
              // 检查分类是否有子分类
              if (category.children && Array.isArray(category.children)) {
                category.children.forEach(subCategory => {
                  // 尝试通过ID或名称查找对应的body数据
                  const matchedBodyItem = bodyMap[subCategory.id] || bodyMap[subCategory.name];

                  if (matchedBodyItem) {
                    // 根据类型处理显示值
                    let displayValue = '';

                    if (matchedBodyItem.choice) {
                      // 处理选择类型的数据
                      if (Array.isArray(matchedBodyItem.choice)) {
                        displayValue = matchedBodyItem.choice.join('、');
                      } else {
                        displayValue = matchedBodyItem.choice;
                      }
                    } else if (matchedBodyItem.content) {
                      // 处理文本类型的数据
                      displayValue = matchedBodyItem.content;
                    } else if (matchedBodyItem.files && matchedBodyItem.files.length > 0) {
                      // 处理文件类型的数据
                      displayValue = matchedBodyItem.files.map(file => file.name).join('、');
                    }

                    // 添加到反馈数据数组
                    if (displayValue) {
                      feedbackData.push({
                        categoryName: subCategory.name,
                        displayValue: displayValue
                      });
                    }
                  }
                });
              }
            });
          }
        } catch (error) {
          console.error('解析form.body失败:', error);
        }
      }

      return feedbackData;
    },



    // 生成反馈内容文本
    generateFeedbackBody() {
      if (!this.feedbackCateList || this.feedbackCateList.length === 0) {
        return ''
      }

      // 构建最终的body数据数组
      const bodyData = []

      // 遍历所有分类和子分类
      this.feedbackCateList.forEach(category => {
        // 确保category.children存在且是数组
        if (category.children && Array.isArray(category.children)) {
          category.children.forEach(subCategory => {
            // 根据不同类型处理数据
            switch (subCategory.type) {
              case 0: // 选项类型
                if (this.dynamicFeedbackOptions[subCategory.id]) {
                  const selectedValues = this.dynamicFeedbackOptions[subCategory.id]
                  if (selectedValues && selectedValues.length > 0) {
                    // 检查是否是文本选项（从description解析的）
                    const hasTextOptions = selectedValues.some(value => typeof value === 'string');

                    if (hasTextOptions) {
                      // 处理文本选项
                      selectedValues.forEach(textOption => {
                        if (typeof textOption === 'string') {
                          bodyData.push({
                            id: subCategory.id,
                            name: subCategory.name,
                            choice: textOption
                          })
                        }
                      })
                    } else if (subCategory.options) {
                      // 处理从options数组中的选项
                      selectedValues.forEach(optionId => {
                        const selectedOption = subCategory.options.find(opt => opt.id === optionId);
                        if (selectedOption) {
                          bodyData.push({
                            id: subCategory.id,
                            name: subCategory.name,
                            choice: selectedOption.name
                          })
                        }
                      })
                    }
                  }
                }
                break

              case 1: // 文本输入类型
                if (this.dynamicFeedbackOptions[subCategory.id]) {
                  const content = this.dynamicFeedbackOptions[subCategory.id]
                  if (content && content.trim()) {
                    bodyData.push({
                      id: subCategory.id,
                      name: subCategory.name,
                      content: content.trim()
                    })
                  }
                }
                break

              case 2: // 文件类型
                if (this.dynamicFeedbackOptions[subCategory.id]) {
                  const files = this.dynamicFeedbackOptions[subCategory.id]
                  if (files && files.length > 0) {
                    bodyData.push({
                      id: subCategory.id,
                      name: subCategory.name,
                      files: files
                    })
                  }
                }
                break
            }
          })
        }
      })

      // 将数据转换为JSON字符串
      return JSON.stringify(bodyData)
    },

    // 生成导出的HTML内容
    generateExportHtml() {
      // 构建导出的HTML结构 - 使用完整的Word兼容格式
      let html = `
        <html xmlns:o="urn:schemas-microsoft-com:office:office"
              xmlns:w="urn:schemas-microsoft-com:office:word"
              xmlns:dt="uuid:C2F41010-65B3-11d1-A29F-00AA00C14882"
              xmlns="http://www.w3.org/TR/REC-html40">
        <!--[if gte mso 9]>
        <xml>
          <w:WordDocument>
            <w:View>Print</w:View>
            <w:Zoom>100</w:Zoom>
            <w:DoNotOptimizeForBrowser/>
            <w:DocumentFormat>Strict</w:DocumentFormat>
            <w:ValidateAgainstSchemas/>
            <w:SaveIfXMLInvalid>false</w:SaveIfXMLInvalid>
            <w:IgnoreMixedContent>false</w:IgnoreMixedContent>
            <w:AlwaysShowPlaceholderText>false</w:AlwaysShowPlaceholderText>
            <w:Compatibility>
              <w:BreakWrappedTables/>
              <w:SnapToGridInCell/>
              <w:WrapTextWithPunct/>
              <w:UseAsianBreakRules/>
              <w:DontGrowAutofit/>
              <w:SplitPgBreakAndParaMark/>
              <w:DontVertAlignCellWithSp/>
              <w:DontBreakConstrainedForcedTables/>
              <w:DontVertAlignInTxbx/>
            </w:Compatibility>
          </w:WordDocument>
        </xml>
        <![endif]-->
        <head>
          <meta charset="UTF-8">
          <meta name="ProgId" content="Word.Document">
          <meta name="Generator" content="Microsoft Word 15">
          <meta name="Originator" content="Microsoft Word 15">
          <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
          <title>日反馈记录表</title>
          <style>
            /* Word文档专用样式 */
            body { 
              font-family: 'SimSun', '宋体', serif;
              font-size: 12pt;
              color: #000000;
              background-color: #ffffff;
              margin: 1.5cm;
              line-height: 1.5;
              width: 160mm;
              max-width: 160mm;
              overflow-x: hidden;
              word-wrap: break-word;
            }
            
            /* A4纸设置 */
            @page {
              size: 210mm 297mm;
              margin: 1.5cm;
              mso-header-margin: 1cm;
              mso-footer-margin: 1cm;
              mso-paper-source: 0;
            }
            
            /* 段落样式 - Word兼容 */
            p { 
              margin-top: 0;
              margin-bottom: 0pt;
              mso-pagination: widow-orphan;
              mso-margin-top-alt: auto;
              mso-margin-bottom-alt: auto;
              text-indent: 0;
              mso-ansi-language: zh-CN;
              word-wrap: break-word;
              max-width: 100%;
              line-height: 1.2;
            }
            
            /* 表格样式 - Word兼容 */
            table { 
              width: 100%;
              max-width: 100%;
              border-collapse: collapse;
              mso-table-layout-alt: fixed;
              mso-yfti-tbllook: 1184;
              mso-padding-alt: 0cm 3pt 0cm 3pt;
              table-layout: fixed;
            }
            
            /* 确保所有容器元素宽度合适 */
            div {
              max-width: 100%;
              overflow-x: hidden;
              word-wrap: break-word;
            }
            
            /* 标题样式调整 */
            .title {
              font-size: 14pt;
              margin-bottom: 0pt;
            }
            
            /* 单元格样式 - Word兼容 */
            td { 
              padding: 4pt;
              border: 1pt solid #000000;
              mso-border-alt: solid #000000 1.0pt;
              mso-padding-alt: 0cm 5.4pt 0cm 5.4pt;
              mso-ansi-language: zh-CN;
              line-height: 1.2;
            }
            
            /* 标题样式 */
            .title { 
              font-weight: bold;
              font-size: 16pt;
              text-align: center;
              margin-bottom: 0pt;
            }
            
            /* 居中段落 */
            .center { 
              text-align: center;
            }
            
            /* 右对齐段落 */
            .right { 
              text-align: right;
            }
            
            /* 加粗文本 */
            strong, b { 
              font-weight: bold;
            }
          </style>
        </head>
        <body>
          <!-- 标题部分 - 使用Word兼容样式 -->
          <p class="title">
            ${this.form.school_name || '厦门市新景幼儿园'} ${this.form.semester_name || '2025-2026 学年第一学期'} ${this.form.class_name || '托大班'}
          </p>
          <p class="title">
            日反馈记录表 <span style="font-size: 12pt; float:right"> 记录人：${this.form.recorder || '-'}</span>
          </p>


          <!-- 基本信息表格 -->
          <table style="margin-bottom: 15pt;">
            <tr>
              <td style="background-color: #f5f5f5; text-align: center; font-weight: bold;">时间</td>
              <td>${this.form.date || '年 月 日'}</td>
              <td style="background-color: #f5f5f5; text-align: center; font-weight: bold;">幼儿姓名</td>
              <td>${this.form.student_name || ''}</td>
              <td style="background-color: #f5f5f5; text-align: center; font-weight: bold;">体温</td>
              <td>${this.form.temperature || ''}</td>
            </tr>
          </table>

          <!-- 反馈内容表格 -->
          <table style="margin-bottom: 10pt; border-collapse: collapse; width: 100%; line-height: 1.2;" cellpadding="4" cellspacing="0">
      `;

      // 添加反馈内容（确保包含今日亮点等所有分类，即使数据为空）
      if (this.feedbackCateList && this.feedbackCateList.length > 0) {
        this.feedbackCateList.forEach((category, categoryIndex) => {
          // 一级事项作为第一列
          html += `
            <tr>
              <td style="border: 1pt solid #000000; padding: 4pt; width: 20%; vertical-align: top;" rowspan="${category.children && category.children.length > 0 ? category.children.length : 1}">
                ${categoryIndex + 1}. ${category.name}
              </td>
          `;

          // 处理顶级事项（如果分类本身有type属性，表示它是一个顶级事项且没有子分类）
          if (category.type !== undefined && (!category.children || category.children.length === 0)) {
            html += '<td style="border: 1pt solid #000000; padding: 4pt; width: 80%;">';

            // 根据顶级事项类型添加内容
            switch (category.type) {
              case 0: // 选项类型 - 显示所有选项，标记选中状态
                const categorySelectedValues = this.dynamicFeedbackOptions[category.id] || [];
                let categoryAllOptions = [];
                
                // 获取所有选项 - 从description或options数组
                if (category.description && category.description.trim()) {
                  // 从description中解析选项
                  categoryAllOptions = category.description.split(';')
                    .map(opt => opt.trim())
                    .filter(opt => opt);
                } else if (category.options && category.options.length > 0) {
                  // 从options数组中获取选项
                  categoryAllOptions = category.options.map(option => option.name);
                }
                
                // 确保显示所有选项，无论是否有选中值
                if (categoryAllOptions.length > 0) {
                  // 显示所有选项，标记选中状态（使用更健壮的判断）
                  categoryAllOptions.forEach((option, idx) => {
                    // 健壮的选中状态判断
                    const isSelected = Array.isArray(categorySelectedValues) && 
                                    (categorySelectedValues.includes(option) || 
                                     categorySelectedValues.includes(option.id) || 
                                     categorySelectedValues.some(v => typeof v === 'object' && v.name === option));
                    const checkMark = isSelected ? '✓' : '□';
                    html += `<span style="margin-right: 15pt; display: inline-block; line-height: 1.2;">${checkMark} ${option}</span>`;
                    if (idx < categoryAllOptions.length - 1) {
                      html += ' ';
                    }
                  });
                } else {
                  // 如果没有预设选项，但有选中值，也需要显示
                  if (Array.isArray(categorySelectedValues) && categorySelectedValues.length > 0) {
                    categorySelectedValues.forEach((value, idx) => {
                      html += `<span style="margin-right: 15pt; display: inline-block; line-height: 1.2;">✓ ${value}</span>`;
                      if (idx < categorySelectedValues.length - 1) {
                        html += ' ';
                      }
                    });
                  }
                }
                break;

              case 1: // 文本输入类型
                // 确保文本内容正确显示，处理可能的空值或非字符串值
                const categoryTextContent = this.dynamicFeedbackOptions[category.id];
                if (categoryTextContent !== undefined && categoryTextContent !== null && categoryTextContent !== '') {
                  html += String(categoryTextContent);
                } else {
                  html += '-';
                }
                break;

              case 2: // 文件类型
                // 更健壮地处理文件数据
                const categoryFileData = this.dynamicFeedbackOptions[category.id];
                if (Array.isArray(categoryFileData) && categoryFileData.length > 0) {
                  const fileNames = categoryFileData.map((file, index) => {
                    const fileName = file && file.name ? file.name : '未命名文件';
                    return `${index + 1}. ${fileName}`;
                  }).join('; ');
                  html += fileNames;
                } else {
                  html += '-';
                }
                break;

              default:
                html += '-';
            }
            html += '</td></tr>';
          } else if (category.children && category.children.length > 0) {
            // 处理子分类（二级事项）
            category.children.forEach((subCategory, childIndex) => {
              // 对于第一个子分类，不需要再次添加一级事项列
              if (childIndex > 0) {
                html += '<tr>';
              }
              
              html += '<td style="border: 1pt solid #000000; padding: 4pt; width: 80%;">';
              html += `<strong>${subCategory.name}:</strong> `;

              // 根据子分类类型和数据添加内容
              switch (subCategory.type) {
                case 0: // 选项类型 - 显示所有选项，标记选中状态
                  const selectedValues = this.dynamicFeedbackOptions[subCategory.id] || [];
                  let allOptions = [];
                  
                  // 获取所有选项 - 从description或options数组
                  if (subCategory.description && subCategory.description.trim()) {
                    // 从description中解析选项
                    allOptions = subCategory.description.split(';')
                      .map(opt => opt.trim())
                      .filter(opt => opt);
                  } else if (subCategory.options && subCategory.options.length > 0) {
                    // 从options数组中获取选项
                    allOptions = subCategory.options.map(option => option.name);
                  }
                  
                  // 确保显示所有选项，无论是否有选中值
                  if (allOptions.length > 0) {
                    // 显示所有选项，标记选中状态（使用更健壮的判断）
                    allOptions.forEach((option, idx) => {
                      // 健壮的选中状态判断
                      const isSelected = Array.isArray(selectedValues) && 
                                      (selectedValues.includes(option) || 
                                       selectedValues.includes(option.id) || 
                                       selectedValues.some(v => typeof v === 'object' && v.name === option));
                      const checkMark = isSelected ? '✓' : '□';
                      html += `<span style="margin-right: 15pt; display: inline-block; line-height: 1.2;">${checkMark} ${option}</span>`;
                      if (idx < allOptions.length - 1) {
                        html += ' ';
                      }
                    });
                  } else {
                    // 如果没有预设选项，但有选中值，也需要显示
                    if (Array.isArray(selectedValues) && selectedValues.length > 0) {
                      selectedValues.forEach((value, idx) => {
                        html += `<span style="margin-right: 15pt; display: inline-block; line-height: 1.2;">✓ ${value}</span>`;
                        if (idx < selectedValues.length - 1) {
                          html += ' ';
                        }
                      });
                    }
                  }
                  break;

                case 1: // 文本输入类型
                  // 确保文本内容正确显示，处理可能的空值或非字符串值
                  const textContent = this.dynamicFeedbackOptions[subCategory.id];
                  if (textContent !== undefined && textContent !== null && textContent !== '') {
                    html += String(textContent);
                  } else {
                    html += '-';
                  }
                  break;

                case 2: // 文件类型
                  // 更健壮地处理文件数据
                  const fileData = this.dynamicFeedbackOptions[subCategory.id];
                  if (Array.isArray(fileData) && fileData.length > 0) {
                    // 对每个文件进行处理
                    fileData.forEach((file, index) => {
                      // 检查是否为图片文件
                      const isImage = this.isImageFile(file);
                      
                      if (isImage && file.url) {
                        // 对于图片，尝试通过img标签嵌入
                        // 注意：直接使用URL可能在Word中不可见，最好是base64，但这里为了简单性先使用URL
                        html += `<div style="margin-bottom: 15pt;">
                                  <span style="display: block; margin-bottom: 5pt; font-size: 12pt;">${index + 1}. ${file.name || '图片'}</span>
                                  <img src="${file.url}" alt="${file.name || '图片'}" style="max-width: 100%; height: auto; max-height: 300pt;" />
                                </div>`;
                      } else {
                        // 非图片文件只显示文件名
                        const fileName = file && file.name ? file.name : '未命名文件';
                        html += `${index + 1}. ${fileName}`;
                      }
                      
                      // 如果不是最后一个文件，添加分隔符
                      if (index < fileData.length - 1) {
                        html += '<br/>';
                      }
                    });
                  } else {
                    html += '-';
                  }
                  break;

                default:
                  html += '-';
              }
              
              html += '</td></tr>';
            });
          }
        });
      } else {
        html += `<tr><td colspan="2" style="border: 1pt solid #000000; padding: 4pt; text-align: center;">暂无反馈数据</td></tr>`;
      }
      
      html += `</table>`;

      html += `
        </body>
        </html>
      `;

      return html;
    },

    // 导出Word文档
    exportToWord() {
      try {
        // 生成HTML内容
        const htmlContent = this.generateExportHtml();

        // 创建Blob对象，使用多种兼容的MIME类型
        const blob = new Blob(['\ufeff' + htmlContent], { 
          type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document;charset=utf-8;application/msword' 
        });

        // 创建下载链接
        const link = document.createElement('a');
        const url = URL.createObjectURL(blob);

        // 设置文件名，使用.docx扩展名
        const fileName = `${this.form.student_name || '幼儿'}_${this.form.date || '无日期'}_日反馈记录.docx`;

        link.href = url;
        link.download = fileName;

        // 触发下载
        document.body.appendChild(link);
        link.click();

        // 清理
        document.body.removeChild(link);
        URL.revokeObjectURL(url);

        this.$message.success('Word文档导出成功');
      } catch (error) {
        console.error('导出Word文档失败:', error);
        this.$message.error('导出Word文档失败，请重试');
      }
    },

    // 关闭弹窗
    closePOpup() {
      this.$emit('update:visible', false);
    },
    
    // 判断是否为图片文件
    isImageFile(file) {
      if (!file) return false;
      
      // 检查文件对象中的类型信息
      if (file.type && file.type.startsWith('image/')) {
        return true;
      }
      
      // 通过文件名后缀判断
      if (file.name) {
        const imgExts = ['.jpg', '.jpeg', '.png', '.gif', '.bmp', '.tiff', '.svg', '.webp'];
        const ext = file.name.toLowerCase().substr(file.name.lastIndexOf('.'));
        return imgExts.includes(ext);
      }
      
      // 检查是否有URL属性，有些图片可能只有URL
      if (file.url) {
        const url = file.url.toLowerCase();
        const imgExts = ['.jpg', '.jpeg', '.png', '.gif', '.bmp', '.tiff', '.svg', '.webp'];
        return imgExts.some(ext => url.includes(ext));
      }
      
      return false;
    }
  },
  mounted() {
    }
}
</script>
<style scoped>
#feedbackRecordForm {
  padding: 20px;
  font-family: "SimSun", "宋体", serif;
}

.feedback-record-container {
  max-width: 900px;
  margin: 0 auto;
  background: #fff;
  padding: 30px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

/* 表头信息样式 */
.header-info {
  text-align: center;
  margin-bottom: 20px;
}

.header-info .title {
  font-size: 18px;
  font-weight: bold;
  color: #333;
  margin-bottom: 10px;
}

.header-info .subtitle {
  font-size: 16px;
  color: #555;
}

/* 记录人信息样式 */
.recorder-info {
  text-align: right;
  margin-bottom: 20px;
  font-size: 14px;
}

.recorder-label {
  color: #555;
}

.recorder-value {
  color: #333;
  display: inline-block;
}

/* 基本信息表格样式 */
.basic-info-table {
  margin-bottom: 20px;
}

.basic-info-table table {
  width: 100%;
  border-collapse: collapse;
  font-size: 14px;
}

.basic-info-table td {
  padding: 10px;
  border: 1px solid #e0e0e0;
}

.info-label {
  background-color: #f5f5f5;
  text-align: center;
  font-weight: bold;
  width: 80px;
}

.info-value {
  text-align: left;
  padding-left: 15px;
}

/* 我的一天标题样式 */
.day-title {
  text-align: center;
  margin-bottom: 20px;
}

.day-title h4 {
  font-size: 16px;
  color: #333;
  margin: 0;
}

/* 选项选中样式 */
.check-r-list-option-list-in {
  position: relative;
  padding-right: 30px; /* 为勾选标记留出空间 */
}

.check-r-list-option-list-in.selected {
  background-color: #f0f8ff;
  border-color: #409eff;
}

.check-icon {
  position: absolute;
  right: 10px;
  top: 50%;
  transform: translateY(-50%);
  color: #409eff;
  font-size: 16px;
  font-weight: bold;
}

/* 文本输入容器样式 */
  .input-container {
    margin-top: 8px;
  }

  .feedback-input {
    width: 300px;
  }

  /* 文件容器样式 */
  .file-container {
    margin-top: 8px;
  }

  .file-preview {
    display: flex;
    flex-wrap: wrap;
    gap: 8px;
  }

  /* 统一行高 */
  body {
    line-height: 1.2;
  }

.file-link {
  display: inline-block;
  padding: 5px 10px;
  background-color: #e6f7ff;
  border: 1px solid #91d5ff;
  border-radius: 4px;
  color: #1890ff;
  text-decoration: none;
  transition: all 0.3s;
}

.file-link:hover {
  background-color: #bae7ff;
  border-color: #40a9ff;
}

.no-file {
  color: #999;
  font-size: 14px;
}
.file-item {
  margin-bottom: 10px;
}
.preview-image {
  max-width: 200px;
  max-height: 150px;
  border: 1px solid #e0e0e0;
  border-radius: 4px;
}
.preview-video {
  max-width: 300px;
  max-height: 200px;
  border: 1px solid #e0e0e0;
  border-radius: 4px;
}

/* 反馈事项表格样式 */
  .feedback-table-wrapper {
    margin-bottom: 10px;
    overflow-x: auto;
    line-height: 1.2;
  }

  .feedback-content-table {
    width: 100%;
    border-collapse: collapse;
    margin-bottom: 10px;
    line-height: 1.2;
  }

  .feedback-content-table td {
    border: 1px solid #e8e8e8;
    padding: 4pt;
    vertical-align: top;
    line-height: 1.2;
  }

  .category-cell {
    width: 150px;
    background-color: #f7f7f7;
    font-weight: bold;
    text-align: center;
    white-space: nowrap;
  }

  .category-number {
    margin-right: 5px;
  }

  .content-cell {
    width: calc(100% - 150px);
  }

  .subcategory-content {
    line-height: 1.2;
  }

  .subcategory-title {
    font-weight: bold;
    margin-right: 8px;
  }

  .subcategory-options {
    display: inline;
  }

  .option-item {
    display: inline-block;
    margin-right: 15px;
    margin-bottom: 5px;
    cursor: pointer;
    padding: 2px 5px;
    border-radius: 4px;
    transition: all 0.3s ease;
    line-height: 1.2;
  }

  .option-item:hover {
    background-color: #f5f7fa;
  }

  .option-item.selected {
    background-color: #e6f7ff;
    border: 1px solid #91d5ff;
  }

  .checkbox {
    margin-right: 3px;
    color: #1890ff;
  }

  .option-text {
    font-size: 14px;
  }

  .no-data {
    text-align: center;
    color: #999;
    padding: 30px;
    font-size: 14px;
  }

.check-r-list-option-list-in:hover {
  border-color: #1890ff;
  background-color: #e6f7ff;
}

.option-title {
    font-size: 14px;
    color: #333;
    line-height: 1.2;
  }



/* 操作按钮样式 */
.action-buttons {
  text-align: center;
  padding: 20px 0;
}

.action-buttons .el-button {
  margin: 0 10px;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .feedback-record-container {
    padding: 15px;
  }

  .header-info .title {
    font-size: 16px;
  }

  .header-info .subtitle {
    font-size: 14px;
  }

  .options-grid {
    flex-direction: column;
  }

  .checkbox-option {
    width: 100%;
  }
}
</style>
